const Router = require('koa-router');
const {pool, fix} = require('./db');

const router = new Router();

router.use('/', async function (ctx, next) {
	ctx.assert(ctx.query.date, 400, '未知的日期');
	await next();
});

router.get('/', async function (ctx) {
	/** @type {string} */
	const datekey = ctx.query.date;
	await pool.query(
		'INSERT INTO daily_log (date, names, comment, cup_size)' +
		'VALUES ($1, DEFAULT, DEFAULT, DEFAULT)' +
		'ON CONFLICT (date) DO NOTHING',
		[datekey]);

	const qConfig = {
		text: 'SELECT names, tags, comment, cup_size ' +
			'FROM daily_log WHERE date = $1 LIMIT 1',
		values: [datekey]
	}
	const result = await pool.query(qConfig);
	const fixedRes = fix(result.rows[0]);

	ctx.body = fixedRes;
});

router.post('/', async function (ctx) {
	/** @type {string} */
	const datekey = ctx.query.date;
	const body = ctx.request.body;

	await pool.query(
		'UPDATE daily_log SET ' +
		'names = $1, comment = $2, cup_size = $3, tags = $4 ' +
		'WHERE date = $5',
		[body.names, body.comment, body.cup_size, body.tags, datekey]);

	ctx.body = {};
});

router.get('/year', async function (ctx) {
	/** @type {string} */
	const year = ctx.query.date;
	const result = await pool.query(
		'SELECT names from daily_log WHERE date >= $1 AND date <= $2',
		[year + '-01-01', year + '-12-31']
	);
	const names = new Set();
	result.rows.forEach(record => {
		record.names.forEach(name => {
			names.add(String(name));
		});
	});

	ctx.body = Array.from(names);
});

module.exports = router;
